package com.yixiu.modules.db.datasources;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;


import java.util.HashMap;
import javax.sql.DataSource;



/**
 * 动态数据源配置类
 * 读取配置文件，初始化数据源
 */
@Configuration
@Profile("dynamic-datasource")
public class DynamicDataSourceConfig {


    private static Logger logger = LoggerFactory.getLogger(DynamicDataSourceConfig.class);


    /**
     * 从配置文件读取节点 spring.datasource.druid.first下的所有配置
     * 注册bean
     * @return
     */
    @Bean
    @ConfigurationProperties( prefix = "spring.datasource.druid.first")
    public DataSource firstDataSource() {
        // 调用druid提供的构造数据源的方法
       DruidDataSource druidDataSource = DruidDataSourceBuilder.create().build();

       return druidDataSource;
    }

    /**
     * 从配置文件读取第2个数据源
     * @return
     */

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid.second")
    public  DataSource secondDataSource(){
        DruidDataSource druidDataSource = DruidDataSourceBuilder.create().build();
        return druidDataSource;
    }

    /**
     * 注入动态数据源
     * @Primary表示当有多个数据源实现时，以这个实现为主
     * @param firstDataSource 第1个数据源
     * @param secondDataSource 第2个数据源
     * @return
     */
    @Bean
    @Primary
    public  DynamicDataSource dataSource( DataSource firstDataSource,DataSource secondDataSource) {
        HashMap<Object,Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceNames.FIRST,firstDataSource);
        targetDataSources.put(DataSourceNames.SECOND,secondDataSource);
        DynamicDataSource dynamicDataSource = new  DynamicDataSource(firstDataSource,targetDataSources);
        return dynamicDataSource;
    }


}
